<template>
    <div class="common-page page-system-appvers" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <!-- <comp-paths class="route" :paths="['/system', $route.fullPath]"></comp-paths> -->
            <div class="title">{{ $options.title }}</div>
        </div>
        <comp-appvers class="common-page__body" ref="list" select link>
            <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addAppver()">添加版本</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="delAppver(...scope.selects)">删除版本</el-button>
            </template>
            <template #body="scope">
                <el-button type="primary" size="mini" @click.stop="setAppver('start', scope.data)">编辑</el-button>
                <el-button type="danger" size="mini" @click.stop="delAppver(scope.data)">删除</el-button>
            </template>
        </comp-appvers>
        <comp-dialog :title="appver && appver.id ? '编辑版本' : '添加版本'" ref="appver">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="appver">
                <el-form-item label="系统类型：" required>
                    <el-select v-model="appver.platform" style="width: 320px" placeholder="请选择" @change="setAppver('validate')">
                        <el-option v-for="data in env.appverPlatforms" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="版本文件：" required v-if="appver.platform === 'android'">
                    <el-tag style="width: 320px" disable-transitions v-if="appver.fileUrl">{{ appver.fileUrl.split("?")[0] }}</el-tag>
                    <div style="height: 10px" v-if="appver.fileUrl"></div>
                    <el-button type="plain" icon="el-icon-plus" style="width: 320px" @click="setAppver('upload')">{{ appver.fileUrl ? "更换文件" : "上传文件" }}</el-button>
                </el-form-item>
                <el-form-item label="版本链接：" required v-else-if="appver.platform === 'ios'">
                    <el-input v-model="appver.filePage" style="width: 320px" placeholder="请输入" :maxlength="200" :readonly="loading" @change="setAppver('validate')"></el-input>
                </el-form-item>
                <el-form-item label="版本号：" required>
                    <el-input v-model="appver.version" style="width: 320px" placeholder="请输入" :maxlength="8" :readonly="loading" @change="setAppver('validate')"></el-input>
                </el-form-item>
                <el-form-item label="版本状态：" required>
                    <el-select v-model="appver.status" style="width: 320px" placeholder="请选择" @change="setAppver('validate')">
                        <el-option v-for="data in env.appverStatus" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setAppver('submit')">{{ appver.id ? "保存" : "添加" }}</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setAppver('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile, deepCopy } from "../util";
    export default {
        name: "page-system-appvers",
        title: "移动应用版本管理",
        nodes: ["/menu/system"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            appver: null,
        }),
        methods: {
            search() {
                if (this.loading) return;
                this.$refs.list.init();
            },
            addAppver() {
                if (this.loading) return;
                let appver = this.plugins.user.formatAppver();
                appver.platform = "android";
                appver.status = "active";
                this.setAppver('start', appver);
            },
            setAppver(action, data) {
                if (this.loading) return;
                let form = this.appver;
                if (!action || action === "start") {
                    this.appver = deepCopy(data);
                    this.setAppver("validate");
                    this.$refs.appver.init();
                } else if (action === "validate") {
                    let error = "";
                    error = error || (form.platform === "android" ? form.fileUrl ? "" : "请上传版本文件！" : "");
                    form.filePage = string(form.filePage).trim();
                    error = error || (form.platform === "ios" ? form.filePage ? "" : "请输入版本链接！" : "");
                    form.version = string(form.version).trim();
                    error = error || (form.version ? /^\d{1,2}\.\d{1,2}\.\d{1,2}$/.test(form.version) ? "" : "版本号格式不正确！" : "请输入版本号！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload") {
                    if (!data) return selectFile("*/*").then((file) => {
                        if (file.size > 100 * 1048576) this.plugins.modal.toast("文件过大，不能大于100MB哦！请重新选择。", "error");
                        else this.setAppver(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "document", progress).then((res) => {
                        if(res.code === 0 && res.data?.objId){
                            this.plugins.user.setFileOpen({
                                id:res.data.objId
                            })
                        }
                        this.loading = false;
                        if (res.code === 0) {
                            form.fileUrl = res.data.name;
                            form.fileId = res.data.id;
                            this.setAppver("validate");
                        } else {
                            this.plugins.modal.alert("文件上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "submit") {
                    if (!this.setAppver("validate", true)) return;
                    else this.loading = true;
                    if (form.id) this.plugins.user.setAppver(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("保存成功！", "success");
                            this.setAppver("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("保存失败", res.code + "：" + res.msg, "error");
                        }
                    });
                    else this.plugins.user.addAppver(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.setAppver("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.appver.close();
                }
            },
            delAppver(...appvers) {
                if (this.loading) return;
                if (appvers.length === 0) return this.plugins.modal.toast("请先勾选要删除的版本哦！", "warning");
                let content = " <span style='color:red;'>" + (appvers.length > 1 ? "勾选的" + appvers.length + "个版本" : appvers[0].version) + "</span> 吗？";
                this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delAppver(...appvers).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-system-appvers {
        overflow: hidden;
    }
</style>
